package hotel.quartz.oversea.job.task;

import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.quartz.UrlMtEnums;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.GsonUtils;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.vo.meituan.MtHotelDetailVo;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import hotel.quartz.oversea.vo.meituan.MtHotelDetailParamVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class MtHhbDownHotelsCheckUpTask {
    private String timestamp = "mslgit"+String.valueOf(System.currentTimeMillis());
    @Autowired
    private RedisService redisService;
    @Autowired
    private RestTemplate restTemplate;
    private void setTimestamp(String timestamp){
        this.timestamp = timestamp;
    }

    //@Async 标识这个方法异步执行，可返回void或Future
    @Async
    public void executeDownCheckUp() {
        log.info("Mt Hhb Down Hotels Check Up Task {} >>>>>>>> 一个月内查询被很好办判断为下线的酒店校验是否上线定时器 执行时间: {}", timestamp, DateUtil.getCurrTime());
        //每天一次查询过去1个月酒店被我们程序主动下线的是否发生上线
        Result rs = getHhbDownHotels();
        if(rs.getCode()== CommonConstants.SUCCESS){
            List<String> ids = (List<String>) rs.getData();
            if(null != ids && ids.size()>0){
                SendUtils.dingMsgNotLog("[执行] 校验程序下线酒店是否可上线 ", DateUtil.getCurrTime()+" 涉及酒店："+ids.size()+" 预计耗时："+ids.size()/2/60+" 分钟", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                List<Long> ten = new ArrayList<>();
                for (int i = 0; i < ids.size(); i++) {
                    if(null != redisService.get("QueuePopBasicSaveMtGoodsInfoJob_checkDownHotelsUp_close")){
                        log.info("executeDownCheckUp程序判断停止");
                        break;
                    }
                    ten.add(Long.valueOf(ids.get(i)));
                    if(ten.size()==10){
                        getHotelDetail(ten);
                        ten = new ArrayList<>();
                    }else{
                        if(i==ids.size()-1){
                            getHotelDetail(ten);
                        }
                    }
                }
                SendUtils.dingMsgNotLog("[结束] 校验程序下线酒店 ", DateUtil.getCurrTime(), MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
        }

        log.info("Mt Hhb Down Hotels Check Up Task {} >>>>>>>> 一个月内查询被很好办判断为下线的酒店校验是否上线定时器 结束时间: {},{}",timestamp, DateUtil.getCurrTime());

    }
    /**
     * 调用美团接口    主动查询上送的酒店是否存在变动数据，有则接口中操作存入缓存队列
     *
     * @return
     */
    private Result request() {
        String host = CommonUrlConstants.MEITUAN_HOST;
        String url = host+ UrlMtEnums.findUpdateGoods.UPDATE_SAVE_HOTEL_BASIC_INFO.getValue();
        Result response = JobRestTemplateUtils.post(url,null,restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.error("静态酒店信息保存更新定时器 调用美团系统接口失败："+ GsonUtils.GsonString(response));
        }
        return response;
    }

    private Result getHhbDownHotels() {
        String host = CommonUrlConstants.MEITUAN_HOST;
        String url = host+ UrlMtEnums.findUpdateGoods.HHB_DOWN_HOTELS.getValue();
        Result response = JobRestTemplateUtils.get(url,null,restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.error("静态酒店主动下线 调用美团接口失败："+ GsonUtils.GsonString(response));
        }
        log.info("获取需校验是否上架酒店：response="+ GsonUtils.GsonString(response));
        return response;
    }

    private Result getHotelDetail(List<Long> ids) {
        if(null != redisService.get("QueuePopBasicSaveMtGoodsInfoJob_checkDownHotelsUp_close")){
            log.info("executeDownCheckUp程序判断停止getHotelDetail");
            return new Result();
        }
        log.info("获取需校验是否上架酒店调用酒店详情接口ids="+ GsonUtils.GsonString(ids));
        String host = CommonUrlConstants.MEITUAN_HOST;
        String url = host+ UrlMtEnums.hotelDetail.GET_FOR.getValue();
        MtHotelDetailParamVo mtHotelDetailParamVo = new MtHotelDetailParamVo();
        mtHotelDetailParamVo.setHotelIds(ids);
        Result response = JobRestTemplateUtils.post(url, GsonUtils.GsonString(mtHotelDetailParamVo),restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.error("调用静态酒店信息定时器 调用美团系统接口失败："+ GsonUtils.GsonString(response));
        }else{
            Map map = new HashMap();
            List<MtHotelDetailVo> hotelids = GsonUtils.jsonToList((String)response.getData(),MtHotelDetailVo.class);
            if(null != hotelids && hotelids.size()>0){
                for (MtHotelDetailVo m:hotelids){
                    if(null != m.getBaseInfo().getCloseStatus() && 0==m.getBaseInfo().getCloseStatus()){
                        map.put(String.valueOf(m.getBaseInfo().getHotelId()),1);
                    }
                }
            }
            List<Long> updateUp = new ArrayList<>();
            for (Long l:ids){
                if(null != map.get(String.valueOf(l))){
                    //酒店上线了（主动查询判断酒店下线是根据详情接口有没有返回数据，结合价格接口）
                    updateUp.add(l);
                }
            }
            if(null != updateUp && updateUp.size()>0){
                log.info("存在主动查询下线的上线了updateUp：", GsonUtils.GsonString(updateUp));
                SendUtils.dingMsgNotLog("[HOTEL-JOB-CHECK] 校验程序下线酒店上线了", DateUtil.getCurrTime()+" "+ GsonUtils.GsonString(updateUp), MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                updateUp(updateUp);
            }

        }
        return response;
    }

    private Result updateUp(List<Long> ids) {
        MtHotelDetailParamVo mtHotelDetailParamVo = new MtHotelDetailParamVo();
        mtHotelDetailParamVo.setHotelIds(ids);
        String host = CommonUrlConstants.MEITUAN_HOST;
        String url = host+ UrlMtEnums.findUpdateGoods.UPDATE_UP.getValue();
        Result response = JobRestTemplateUtils.post(url, GsonUtils.GsonString(mtHotelDetailParamVo),restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.error("静态酒店主动查询上线 调用美团接口失败："+ GsonUtils.GsonString(response));
        }
        return response;
    }


}
